#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import sys
import zipfile

from utils import simple_run, print_track


def detail(ipa, icon_dir):
    if not os.path.exists(ipa):
        raise Exception("ipa不存在[%s]" % ipa)
    zf = zipfile.ZipFile(ipa, mode='r')
    info_plist = filter(lambda x: str(x).endswith('/Info.plist'), zf.namelist())
    if len(info_plist) != 1:
        raise Exception("ipa不合法[%s]" % ipa)
    prefix = os.path.dirname(info_plist[0])
    info_plist = zf.read(info_plist[0])

    try:
        import biplist
        biplist_init = True
    except:
        biplist_init = False

    if biplist_init:
        import biplist
        plist = biplist.readPlistFromString(info_plist)
        title = plist["CFBundleDisplayName"].encode("utf8")
        icons = plist["CFBundleIcons"]["CFBundlePrimaryIcon"]["CFBundleIconFiles"]
        icon = icons[-1]
    elif os.path.exists('/usr/libexec/PlistBuddy'):
        import tempfile
        ftmp = tempfile.mkstemp()[1]
        with open(ftmp, mode='wb') as fout:
            fout.write(info_plist)
        title = simple_run('/usr/libexec/PlistBuddy -c "Print CFBundleDisplayName" %s' % ftmp)
        icon = simple_run(
            '/usr/libexec/PlistBuddy -c "Print :CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles:0" %s' % ftmp).strip()
    else:
        raise Exception("无法解析ipa[%s]可以通过引入biplist解决" % ipa)
    icon = filter(lambda x: str(x).startswith(prefix + '/' + icon), zf.namelist())
    if len(icon) >= 1:
        icon = os.path.basename(icon[0])
        with open(os.path.join(icon_dir, "Icon.png"), mode='wb') as fout:
            fout.write(zf.read(os.path.join(prefix, icon)))
        icon = "Icon.png"
    else:
        icon = None
    zf.close()
    return title, icon


def JenkinsPlist(jenkins_home, job_name, build_number, ipa, bundle_id, output):
    data = {
        'id': bundle_id,
        'ipa': '%s/job/%s/%s/artifact/%s' % (jenkins_home, job_name, build_number, ipa),
        'icon': "",
        'title': job_name,
        'version': build_number
    }
    output_dir = os.path.dirname(output)
    try:
        ret = detail(os.path.join('..', ipa), icon_dir=output_dir)
        data['title'], data['icon'] = ret
        if data['icon'] is not None:
            data['icon'] = '%s/job/%s/%s/artifact/%s/%s' % \
                           (jenkins_home, job_name, build_number, os.path.dirname(ipa), data['icon'])
        # patch: 找到安装不显示图标的原因前暂时屏蔽
        data['icon'] = ""
    except:
        print_track()
    with open(output, mode='w') as fout:
        fout.write('''\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>items</key>
   <array>
       <dict>
           <key>assets</key>
           <array>
               <dict>
                   <key>kind</key>
                   <string>software-package</string>
                   <key>url</key>
                   <string>%(ipa)s</string>
               </dict>
               <dict>
                   <key>kind</key>
                   <string>display-image</string>
                   <key>needs-shine</key>
                   <true/>
                   <key>url</key>
                   <string>%(icon)s</string>
               </dict>
           </array><key>metadata</key>
           <dict>
               <key>bundle-identifier</key>
               <string>%(id)s</string>
               <key>bundle-version</key>
               <string>%(version)s</string>
               <key>kind</key>
               <string>software</string>
               <key>subtitle</key>
               <string>%(title)s</string>
               <key>title</key>
               <string>%(title)s</string>
           </dict>
       </dict>
   </array>
</dict>
</plist>
''' % data)
    pass


if __name__ == '__main__':
    if len(sys.argv) < 7:
        print """\
Usage:
    JenkinsPlistHelper.py <JENKINS_HOME> <JOB_NAME> <BUILD_NUMBER> <IPA> <BUNDLE_ID> <OUTPUT>
"""
        exit(0)
    JenkinsPlist(*sys.argv[1:])
